package com.aopcinemas.cinema.dao;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.sql.Statement;

import org.apache.commons.lang3.StringUtils;

public class DBUtil {

    public static void generateDBIfNotExists(Connection connection) {
        // shit code
        Statement st;
        try {
            st = connection.createStatement();
        } catch (SQLException e) {
            throw new RuntimeException("System error", e);
        }
        boolean generate = false;

        try {
            st.executeQuery("select * from hall");
        } catch (SQLException e) {
            generate = true;
        }

        if (generate) {
            String[] sqls = readSqls("cinema.sql");
            for (String sql : sqls) {
                if (StringUtils.isNotBlank(sql)) {
                    try {
                        // System.out.println("execute: " + sql);
                        PreparedStatement prst = connection.prepareStatement(sql);
                        prst.execute();
                        prst.close();
                    } catch (SQLException e) {
                        throw new RuntimeException("Can execute sql query: " + sql, e);
                    }
                }
            }
        }

        try {
            connection.commit();
            st.close();
        } catch (SQLException e) {
            throw new RuntimeException("System error", e);
        }

    }

    static String[] readSqls(String file) {
        String[] sqls = new String[] {};
        try {
            InputStream sqlIn = ClassLoader.getSystemResourceAsStream(file);
            InputStreamReader reader = new InputStreamReader(sqlIn, "utf-8");
            BufferedReader bufferedReader = new BufferedReader(reader);
            StringBuilder builder = new StringBuilder(1000);

            String line;
            while ((line = bufferedReader.readLine()) != null) {
                builder.append(line);
                builder.append(' ');
            }
            sqls = builder.toString().split(";--end");
        } catch (IOException e) {
            e.printStackTrace();
        }
        return sqls;
    }

}
